package com.skywolf.chem.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.skywolf.chem.common.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @ClassName BaseEntityHandler.java
 * @Author Leo
 * @Version 1.0.0
 * @Description Leo
 * @CreateTime 2019年09月18日 21:42:00
 */
@Component
@Slf4j
public class BaseEntityHandler implements MetaObjectHandler {

    private static final Long DEFAULT_USER_ID = 0L;

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setInsertFieldValByName("createdBy", RequestContext.getLoginUser() != null ? RequestContext.getLoginUser().getId() : DEFAULT_USER_ID, metaObject);
        this.setInsertFieldValByName("updatedBy", RequestContext.getLoginUser() != null ? RequestContext.getLoginUser().getId() : DEFAULT_USER_ID, metaObject);
        this.setInsertFieldValByName("createdTime", LocalDateTime.now(), metaObject);
        this.setInsertFieldValByName("updatedTime", LocalDateTime.now(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setUpdateFieldValByName("updatedBy", RequestContext.getLoginUser() != null ? RequestContext.getLoginUser().getId() : DEFAULT_USER_ID, metaObject);
        this.setUpdateFieldValByName("updatedTime", LocalDateTime.now(), metaObject);
    }
}
